package com.jackrain.nea.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static java.lang.Boolean.TRUE;
import static org.apache.shiro.SecurityUtils.getSubject;

/**
 * Created by nathan on 2016/7/27.
 */

@RestController
@Api(value = "登录")
public class LoginController {

    public final Logger logger = Logger.getLogger(LoginController.class);

    private TryLoginUtil tryLoginUtil = new TryLoginUtil();



    @Autowired
    private UpdatePwdHash updatePwdHash;


    /**
     * 登录检验
     * @return
     */
    @ApiOperation(value = "登录检验")
    @RequestMapping(path = "/p/cs/rememberMeLogin",method = RequestMethod.GET)
    public JSONObject rememberMeLogin(){
        Subject subject = getSubject();
        ValueHolder valueHolder = new ValueHolder();
        if (subject != null && (subject.isAuthenticated()||subject.isRemembered())){
            valueHolder.put("user",subject.getPrincipal());
            valueHolder.put("code",1);
        }else{
            valueHolder.put("message", Resources.getMessage("login-rememberMe-fail"));
            valueHolder.put("code",-1);
        }
        return valueHolder.toJSONObject();
    }


    /**
     * 登录方法
     * @param request
     * @param response
     * @param session
     * @return
     */
    @ApiOperation(value = "登录")
    @RequestMapping(path = "/p/c/login",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject login(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        ValueHolder valueHolder = new ValueHolder();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        Boolean rememberMe = TRUE;//Boolean.valueOf(request.getParameter("rememberMe"));
        Subject subject = SecurityUtils.getSubject();
        String IP = WebUtils.getIpAddress(request);//获取客户端IP
        WebUtils webUtils = new WebUtils();

//        if (StringUtils.isEmpty(captcha)){
//            valueHolder.put("code",-1);
//            valueHolder.put("msg","captcha is null");
//            return valueHolder.toJSONObject();
//        }
//        //验证
//        boolean gtResult = webUtils.verCaptcha(captcha);
//        if (!gtResult){
//            valueHolder.put("code",-1);
//            valueHolder.put("msg",Resources.getMessage("Verification_code_error"));
//            return valueHolder.toJSONObject();
//        }

        if(tryLoginUtil.tryLogin(username,password,rememberMe,subject,IP)){
            subject.getSession().setAttribute("user",subject.getPrincipal());
            valueHolder.put("user",subject.getPrincipal());
            valueHolder.put("code",1);
        }else {
            String message = "";
            ValueHolder vh = (ValueHolder)ShiroSessionUtil.getAttribute("vh");
            if (vh != null && !"".equals(vh)){
                message = (String) vh.get("message");
            }
            valueHolder.put("code",-1);
            valueHolder.put("msg",message);
            return valueHolder.toJSONObject();
        }
        return valueHolder.toJSONObject();
    }

    @RequestMapping(path = "/p/cs/logout",method = RequestMethod.GET)
    public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        for (int i = 0;i<cookies.length;i++){
            Cookie v = cookies[i];
            if (v.getName().equals("verificationSafe")){
                v.setMaxAge(0);
                response.addCookie(v);
            }
        }
        Subject subject = getSubject();
        subject.logout();
        response.sendRedirect("/");
    }

    @RequestMapping(path = "/p/cs/touch",method = RequestMethod.GET)
    public void touch(){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.touch();
    }

}
